package chat.server;

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import chat.user.Group;
import chat.user.Message;
import chat.user.User;

public class SocketWriter implements Runnable {
	
	//private Socket socket;
	//private c oos;
	private SocketProcessor socket_processor;
	private ObjectOutputStream oos;
	Object sync = new Object();
	
	public SocketWriter() throws IOException{
		
	}
	
	@Override
	public synchronized void run(){
		
		try {
			
			while (true){
				
				synchronized(sync){
				
				//Thread.sleep(500);
				
				while (SocketProcessor.getCountOutQueue()>0){
				
						/*Message m = SocketProcessor.getMessage();
						
						Group g = GroupProcessor.getGroup(m.getUser().getRelatedGroup());
						
						HashMap<String, Socket> socket_list = g.getUserSocketList();
						
						for (Map.Entry<String, Socket> entry: socket_list.entrySet()){
							
							Socket socket = entry.getValue();
							
							BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
							ObjectOutputStream oos = new ObjectOutputStream(out);
								
							oos.writeObject(m);
							oos.flush();
							
						}*/
					
						Message m = SocketProcessor.getMessage();
						
						User user_copy = (User) m.getUser().clone(); 
						
						Socket socket = user_copy.getSocket();
						
						user_copy.removeSocket();
						
						m.setUser(user_copy);
						
						BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
						ObjectOutputStream oos = new ObjectOutputStream(out);
							
						oos.writeObject(m);
						oos.flush();
					
					SocketProcessor.removeMessageOutQueue(m);
				}
			}
		}}
		catch (Exception e){
			
			e.printStackTrace();
		}
		
	}
	
	/*public void requestAuthentification(){
		
		try {
			
			Message m = new Message();
			m.AUTH_REQUEST=true;
			
			oos.writeObject(m);
			oos.flush();
		}
		catch (IOException e){
			
			e.printStackTrace();
		}
	}*/
}
